package org.huangrui.juc.source.Interrupt;

import org.junit.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 中断运行中线程
 * @Author hr
 * @Create 2024-04-02 09:33
 */
public class T01_Interrupt {
    static volatile boolean isStop = false;
    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "\t Interrupted被修改为true，程序停止");
                    break;
                }
                System.out.println("t1 -----hello Interrupted");
            }
        }, "t1");
        t1.start();
        System.out.println("-----t1的默认中断标志位："+t1.isInterrupted());
        //暂停10毫秒
        try { TimeUnit.MILLISECONDS.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}
        // t2向t1发出协商，将t1的中断标志位设为true希望t1停下来
        // new Thread(() ->{ t1.interrupt(); },"t2").start();
        // 也可以自己停自己
        t1.interrupt();
    }
    @Test
    public void m2AtomicBoolean() {
        new Thread(() -> {
            while (true){
                if(atomicBoolean.get()){
                    System.out.println(Thread.currentThread().getName()+"\t atomicBoolean被修改为true，程序停止");
                    break;
                }
                System.out.println("t1 -----hello atomicBoolean");
            }
        },"t1").start();

        //暂停毫秒
        try { TimeUnit.MILLISECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            atomicBoolean.set(true);
        },"t2").start();
    }
    @Test
    public void m1volatite() {
        new Thread(() ->{
           while (true){
               if (isStop){
                     System.out.println(Thread.currentThread().getName()+"\t --isStop被修改为true，程序停止");
                     break;
               }
               System.out.println("t1 ------volatile");
           }
        },"t1").start();
        // 暂停毫秒
        try { TimeUnit.MILLISECONDS.sleep(10); } catch (InterruptedException e) { throw new RuntimeException(e); }

        new Thread(()->{
            isStop = true;
        },"t2").start();
    }
}
